import logging

from loginserver.lib.base import *
import httplib, urllib, urllib2
from indra.base import llsd

log = logging.getLogger(__name__)


def CAP(data):
    """post to an url"""
    host = config['loginserver.capsserver.host']
    port = config['loginserver.capsserver.port']
    path = config['loginserver.capsserver.path']
    params = urllib.urlencode({'data': llsd.format_xml(data)})
    headers = {"Accept": "text/plain", 'Content-Type':'application/x-www-form-urlencoded'}

    conn = httplib.HTTPConnection(host,port)
    conn.request("POST", path, params, headers)
    r1 = conn.getresponse()
    resdata = r1.read()
    conn.close()
    return resdata



class LoginController(BaseController):

    def do(self):
        """do the login
        
        we expect data encoded as LLSD with the following keys:
        
        username -- the username (e.g. Firstname Lastname)
        credentials -- probably the password (or webkey?)
        
        we return the seed capability encoded in LLSD
        
        """
        
        username = request.POST['username']
        credentials = request.POST['credentials']
        
        # check if they authenticate
        # Hm.. guess they do
        # 
        
        # create seed capability by talking to the capsserver
        data={
                'origin'    : 'http://localhost:5100/seed/respond',
                'title'     : 'seedcap',
            }

        return llsd.format_xml({'seed-capability':CAP(data)})
        
        
        
        
        
